<?php

namespace app\common\validate;

use think\Validate;
use think\Db;

class User extends Validate {

    //定义验证规则
    protected $rule = [
        'mobile|手机号' => 'checkMobile:thinkphp|require',
        'name|名称' => 'require',
        'avatar|头像' => 'require',
        'IDCards|身份证' => 'checkIDCard:thinkphp|require',
        'isGoodEmployer|是否好雇主' => 'number|between:0,1',
    ];
    //定义验证提示
    protected $message = [];

    /**
     * 检查手机号 加入了唯一验证
     *
     */
    protected function checkMobile($value, $rule, $data) {
        $res = true;
        if (!checkMobile($value)) {
            $res = "手机号码不正确！";
        } else{
            if(input('cid')){
                $user = model('user')->where(['mobile' => $value, 'id' => ['<>', input('cid')]])->find();
            } else {
                $user = model('user')->where(['mobile' => $value])->find();
            }
            $res = $user ? '该手机号已被注册！' : true;
        }
        return $res;
    }

    /**
     * 检查身份证 加入了唯一验证
     *
     */
    protected function checkIDCard($value, $rule, $data) {
        $res = true;
        if (!checkIDCard($value)) {
            $res = "身份证不正确！";
        } else{
            if(input('cid')){
                $user = Db::name('user')->where(['IDCards' => $value, 'id' => ['<>', input('cid')]])->find();
            } else {
                $user = Db::name('user')->where(['IDCards' => $value])->find();
            }
            $res = $user ? '该身份证已被使用！' : true;
        }
        return $res;
    }

    /**
     * 检查账号 加入了唯一验证
     *
     */
    protected function checkAccount($value) {
        $res = true;
        if(preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]+$/u',$value)){
            $res = "账号只能由英文、数字、下划线组成！";
        } else {
            //$admin = model('user')->where([''])
        }
        return $res;
    }
}
